package com.tmpt.utils.net;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;

import com.tmpt.utils.Config;

import java.io.*;
import java.util.*;


public class SendMail
{

	//发送邮件
	public static void sendMailTo(String host,String from,String username,String password,String to,String fileAttachment, String title, String content) throws IOException{
    
        try{
        // Get system properties
        // Properties props = System.getProperties(); 很多例子中是这样的，其实下面这句更好，可以用在applet中
        Properties props = new Properties();

        // Setup mail server
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true"); //这样才能通过验证

        // Get session
        Session session = Session.getDefaultInstance(props);

        // watch the mail commands go by to the mail server
        session.setDebug(true);

        // Define message
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, to);
        message.setSubject(title);

        Multipart multipart = new MimeMultipart();
        //放内容附件
		MimeBodyPart messageBodyPart = new MimeBodyPart();
		messageBodyPart.setText(content);
		multipart.addBodyPart(messageBodyPart);
        //放内容附件Attachment
		if(fileAttachment!=null){
			messageBodyPart = new MimeBodyPart();
			DataSource source = new FileDataSource(fileAttachment);
			messageBodyPart.setDataHandler(new DataHandler(source));
			File f = new File(fileAttachment);
			messageBodyPart.setFileName(f.getName());
		}
		
		multipart.addBodyPart(messageBodyPart);
           
        message.setContent(multipart);
        // Send message
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

        }catch(Exception e){
        	e.printStackTrace();
        }
    
	}
	
	public static void sendMailTo(String title, String content){
		try {
			sendMailTo(Config.host, Config.email, Config.user, Config.password, Config.toEmail, null, title, content);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void sendMailTo(String toEmail,String title, String content){
		try {
			sendMailTo(Config.host, Config.email, Config.user, Config.password, toEmail, null, title, content);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//main
    public static void main(String args[]) throws Exception
    {
    	SendMail.sendMailTo("titleaaa","contentaaaa");
    }
    
} 
